from config_manager import config
from cache_manager import get_cached_analysis, save_analysis_to_db
from stock_data_provider import get_stock_data
from stock_info_provider import get_stock_name, get_stock_industry
from technical_analyzer import calculate_indicators
from ai_analyzer import call_deepseek_api, generate_stock_analysis_prompt

# 当前正在分析的股票和进度
analysis_status = {
    'symbol': None,
    'status': 'idle',  # idle, processing
    'step': None,
    'percentage': 0
}

def generate_stock_analysis(symbol):
    """生成股票分析报告"""
    print(f"开始分析股票: {symbol}")
    
    # 更新分析状态
    global analysis_status
    analysis_status['symbol'] = symbol
    analysis_status['status'] = 'processing'
    analysis_status['step'] = '检查缓存'
    analysis_status['percentage'] = 0
    
    # 首先检查数据库缓存
    cached_result = get_cached_analysis(symbol)
    if cached_result:
        # 更新状态
        analysis_status['step'] = '从缓存获取结果'
        analysis_status['percentage'] = 100
        
        # 从缓存结果构建返回数据
        result = {
            "symbol": cached_result['symbol'],
            "stock_name": cached_result['stock_name'],
            "industry": cached_result['industry'],
            "indicators": cached_result['indicators'],
            "analysis": cached_result['analysis'],
            "from_cache": True,
            "cached_at": cached_result['created_at'].strftime('%Y-%m-%d %H:%M:%S')
        }
        
        # 重置状态
        analysis_status['status'] = 'idle'
        analysis_status['percentage'] = 0
        
        return result
    
    # 缓存不存在或已过期，重新生成分析
    try:
        # 获取股票数据
        analysis_status['step'] = '获取股票数据'
        analysis_status['percentage'] = 20
        data = get_stock_data(symbol, config['lookback_days'])
        if data is None or (hasattr(data, 'empty') and data.empty):
            # 重置状态
            analysis_status['status'] = 'idle'
            analysis_status['percentage'] = 0
            return {"error": f"无法获取股票 {symbol} 的数据，请检查股票代码是否正确"}

        # 获取股票名称
        analysis_status['step'] = '获取股票名称'
        analysis_status['percentage'] = 30
        stock_name = get_stock_name(symbol)

        # 计算技术指标
        analysis_status['step'] = '计算技术指标'
        analysis_status['percentage'] = 50
        indicators = calculate_indicators(data)

        # 获取股票行业信息
        analysis_status['step'] = '获取行业信息'
        analysis_status['percentage'] = 60
        stock_industry = get_stock_industry(symbol)
        
        # 准备DeepSeek提示
        analysis_status['step'] = '准备分析提示'
        analysis_status['percentage'] = 70
        prompt = generate_stock_analysis_prompt(
            symbol, stock_name, stock_industry, indicators, config['lookback_days']
        )

        # 调用DeepSeek API获取分析
        analysis_status['step'] = '调用AI分析'
        analysis_status['percentage'] = 80
        analysis = call_deepseek_api(prompt)
        
        # 构建分析结果
        analysis_status['step'] = '构建分析结果'
        analysis_status['percentage'] = 90
        # 提取纯股票代码（去掉交易所后缀）
        pure_symbol = symbol.split('.')[0]
        result = {
            "symbol": symbol,
            "stock_name": stock_name or f"股票{pure_symbol}",
            "industry": stock_industry,
            "indicators": indicators,
            "analysis": analysis,
            "from_cache": False
        }
        
        # 保存到数据库
        analysis_status['step'] = '保存到数据库'
        analysis_status['percentage'] = 95
        save_analysis_to_db(symbol, result)
        
        # 重置状态
        analysis_status['step'] = '完成'
        analysis_status['percentage'] = 100
        analysis_status['status'] = 'idle'

        return result
    except Exception as e:
        error_msg = str(e)
        print(f"股票分析过程中出错: {error_msg}")
        # 重置状态
        analysis_status['status'] = 'idle'
        analysis_status['percentage'] = 0
        # 处理AkShare相关的错误
        if "AkShare" in error_msg:
            return {"error": f"数据获取失败: {error_msg}"}
        # 其他错误
        return {"error": f"分析失败: {error_msg}"}
